/* eslint-disable no-undef */
/* eslint-disable no-unused-vars */
import { postLog } from '@/utils/errLogReport'
import { parseParams, httpErrorInterceptor401 } from '@/utils/common'

export default async function request(opts) {
  const opt = opts || {}
  opt.url = opt.url.includes('http') ? opt.url : `${getApp().globalData.apiUrl}${opt.url}`
  opt.url = parseParams(opt.url, {
    tokenid: uni.getStorageSync('tokenid'),
  })
  opt.data = opt.data || {}
  opt.header = opt.header || {}
  opt.header['Content-Type'] = 'application/json'
  // #ifdef MP-WEIXIN
  opt.header['X-Cfpamf-App-Key'] = '70ee5b0e-8e7d-406c-b874-4ed2c26e9f98'
  // #endif

  // #ifdef H5
  opt.header['X-Cfpamf-App-Key'] = '84f94dba-425f-4eb7-bb8a-fd995a6f6105'
  // #endif


  if (opt.method === 'POST') {
    return new Promise((resolve, reject) => {
      requestPost(opt, resolve, reject)
    }).then((res) => {
      // 错误日志上报，根据后台返回状态码
      if ((res && res.status && res.status !== 200) || (res && res.code && res.code !== '000000')) {
        postLog(res, opt.url, opt.data, 'POST')
      }
      return res
    })
  } else {
    return new Promise((resolve, reject) => {
      requestGet(opt, resolve, reject)
    }).then((res) => {
      if ((res && res.status && res.status !== 200) || (res && res.code && res.code !== '000000')) {
        postLog(res, opt.url, opt.data, 'GET')
      }
      return res
    })
  }
}

function requestGet(opts, resolve, reject) {
  const opt = opts || {}
  opt.url = opt.url || ''
  opt.data = opt.data || {}
  opt.header = opt.header || {}
  uni.request({
    url: opt.url,
    data: opt.data,
    method: 'GET',
    header: opt.header,
    dataType: 'json',
    success: (res) => {
      const { 'x-cfpamf-auth-token': tokenid } = res.header
      if (tokenid) {
        uni.setStorageSync('tokenid', tokenid)
      }
      if (res.data.state === 401 || res.data.status === 401) {
        httpErrorInterceptor401()
      } else {
        resolve(res.data)
      }
    },
    fail: (err) => {
      reject(err)
    },
    complete: (res) => {
    },
  })
}

function requestPost(opts, resolve, reject) {
  const opt = opts || {}
  opt.url = opt.url || ''
  opt.data = opt.data || null
  opt.header = opt.header || {}
  uni.request({
    url: opt.url,
    data: opt.data,
    method: 'POST',
    header: opt.header,
    dataType: 'json',
    success: (res) => {
      const { 'x-cfpamf-auth-token': tokenid } = res.header
      if (tokenid) {
        uni.setStorageSync('tokenid', tokenid)
      }
      if (res.data.state === 401 || res.data.status === 401) {
        httpErrorInterceptor401()
      } else {
        resolve(res.data)
      }
    },
    fail: (err) => {
      reject(err)
    },
    complete: (res) => {

    },
  })
}

